package org.mall.modules.statistics.controller.pay;

import lombok.extern.slf4j.Slf4j;
import org.mall.common.api.vo.CommonResult;
import org.mall.common.api.vo.Result;
import org.mall.common.system.util.JwtUtil;
import org.mall.common.util.MapSortUtil;
import org.mall.common.util.ObjectUtils;
import org.mall.common.util.TimeUtils;
import org.mall.modules.order.service.OrderService;
import org.mall.modules.pojo.order.bo.OrderBO;
import org.mall.modules.pojo.order.bo.OrderItemBO;
import org.mall.modules.pojo.order.bo.OrderPayAllChartBO;
import org.mall.modules.pojo.order.vo.OrdersVO;
import org.mall.modules.pojo.shop.ShopDTO;
import org.mall.modules.shop.service.ShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: LL
 * @Date: 2019/12/13 10:45
 */
@RestController
@RequestMapping("/payChart")
@Slf4j
public class PayStatisticsController {
    @Autowired
    OrderService orderService;
   @Autowired
   ShopService shopService;

    /**
     * type 3 获取商户 各个商店本月的销售额 已排序 降序
     * @param ordersVO
     * @return
     */
    @GetMapping("/merchant/rightmonth")
    public Result<?> getRightMonth(OrdersVO ordersVO){
        List<ShopDTO> data = shopService.getListOfStores(JwtUtil.getUserIdByToken()).getData();
        List<String> shopIds = data.stream().map(ShopDTO::getId).collect(Collectors.toList());
        ordersVO.setShopIds(shopIds);
        CommonResult<List<OrderPayAllChartBO>>  orderChartBO= null;
        Map<String, List<OrderPayAllChartBO>> result=null;
            orderChartBO = orderService.getpayMonth(ordersVO);
            CommonResult<List<ShopDTO>> shopNames= shopService.getShopInfoById(shopIds);
        return Result.ok(orderChartBO.getData().stream().map(a-> ObjectUtils.copyObject(a,OrderPayAllChartBO.class)
        .setShopName(shopNames.getData().stream()
        .filter(shopDTO -> shopDTO.getId().equals(a.getShopId()))
        .map(ShopDTO::getShopName)
        .findFirst().orElse(""))).collect(Collectors.toList())
                .stream().sorted(Comparator.comparing(OrderPayAllChartBO::getPresentPrice).reversed()).collect(Collectors.toList()));
    }

    /**
     * 获取商户一周 2 一月 3 一年 4 销售 柱状图使用
     * @param ordersVO
     * @return
     */
    @GetMapping("/merchant/monthofYear")
    public Result<?> getMonthofYear(OrdersVO ordersVO)  {
        List<ShopDTO> data = shopService.getListOfStores(JwtUtil.getUserIdByToken()).getData();
        List<String> shopIds = data.stream().map(ShopDTO::getId).collect(Collectors.toList());
        ordersVO.setShopIds(shopIds);
        Map<String, Integer> resultMap = null;
        int[] result={0,0,0,0,0,0,0,0,0,0,0,0};
        try {
            resultMap = orderService.getpayMonthofYear(ordersVO);
            Iterator<String> iterator=resultMap.keySet().iterator();
            while (iterator.hasNext()){
                String key=iterator.next();
                int index=Integer.parseInt(key);
                result[index]=resultMap.get(key);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.ok(result);
    }
    @GetMapping("/merchant/month")
    public Result<?> getMonth(OrdersVO ordersVO)  {
        List<ShopDTO> data = shopService.getListOfStores(JwtUtil.getUserIdByToken()).getData();
        List<String> shopIds = data.stream().map(ShopDTO::getId).collect(Collectors.toList());
        ordersVO.setShopIds(shopIds);
        Map<String, Integer> resultMap = null;
        Map<String, Integer> stringIntegerMap = null;
        try {
            resultMap = orderService.getpayMonthofYear(ordersVO);
            stringIntegerMap = MapSortUtil.sortByKeyAsc(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.ok(stringIntegerMap);
    }
    @GetMapping("/merchant/zhou")
    public Result<?> getzhou(OrdersVO ordersVO)  {
        List<ShopDTO> data = shopService.getListOfStores(JwtUtil.getUserIdByToken()).getData();
        List<String> shopIds = data.stream().map(ShopDTO::getId).collect(Collectors.toList());
        ordersVO.setShopIds(shopIds);
        Map<String, Integer> resultMap = null;
        Map<String, Integer> stringIntegerMap = null;
        try {
            resultMap = orderService.getpayMonthofYear(ordersVO);
            stringIntegerMap = MapSortUtil.sortByKeyAsc(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.ok(stringIntegerMap);
    }

    /**
     * 5 折线图 获取商户 各个店铺一个月的销售额
     * @param ordersVO
     * @return
     */
    @GetMapping("/merchant/bottomMonth")
    public CommonResult getBottomMonth(OrdersVO ordersVO){
        List list ;
        List<String> shopIds ;
        SimpleDateFormat fmt = new SimpleDateFormat("dd");
        Map<String,Integer> map ;
        Map<String,List<Map<String,Integer>>> shopMap = new HashMap<>();
        Long monthStartTimes = TimeUtils.getMonthStartTime(System.currentTimeMillis(), "GMT+8:00");
        String s5 = TimeUtils.timestampToStr(monthStartTimes);
        Long monthEndTimes = TimeUtils.getMonthEndTime(System.currentTimeMillis(), "GMT+8:00");
        String s6 = TimeUtils.timestampToStr(monthEndTimes);
        ordersVO.setStartCreateTime(s5);
        ordersVO.setEndCreateTime(s6);

        //获取商铺ID和商铺名称
        List<ShopDTO> data = shopService.getListOfStores(JwtUtil.getUserIdByToken()).getData();
        if (data == null || data.size() == 0){
            return CommonResult.error("没有店铺信息");
        }
        shopIds = data.stream().map(ShopDTO::getId).collect(Collectors.toList());
        ordersVO.setShopIds(shopIds);

        //获取当月每个店铺每天的营业额
        List<OrderBO> listCommonResult = orderService.getpayMonthForSalesVolume(ordersVO).getData();
        if(listCommonResult == null || listCommonResult.isEmpty()){
            return CommonResult.error("本月该店铺没有营业额");
        }
        for(int i = 0; i < data.size(); i++){
            list = new ArrayList();
            map = new HashMap<>();
            ShopDTO shopDTO = data.get(i);
            for(int j = 0; j < listCommonResult.size(); j++){
                OrderBO bo = listCommonResult.get(j);
                if(bo.getShopId().equals(shopDTO.getId())){
                    if (map.containsKey(fmt.format(bo.getClosingTime()))) {
                        int monthPrices = map.get(fmt.format(bo.getClosingTime())) + (bo.getPresentPrice() == null?0:bo.getPresentPrice());
                        map.put(fmt.format(bo.getClosingTime()), monthPrices);
                    } else {
                        map.put(fmt.format(bo.getClosingTime()),(bo.getPresentPrice() == null?0:bo.getPresentPrice()));
                    }
                    if (!list.contains(map)){
                        list.add(map);
                    }
                }
            }
            shopMap.put(shopDTO.getShopName(),list);
        }
        return CommonResult.success(shopMap);
    }

    /**
     * 获取当前用户下所有店铺的销售额
     * @return
     */
    @GetMapping("/getSalesVolumes")
    public Result getSalesVolumes(){
        List<ShopDTO> data = shopService.getListOfStores(JwtUtil.getUserIdByToken()).getData();
        if (data == null || data.size() == 0){
            return Result.error("没有店铺信息");
        }
        List<String> shopIds = data.stream().map(ShopDTO::getId).collect(Collectors.toList());
        Map<String, Object> salesVolumes = orderService.getSalesVolumes(shopIds);

        return Result.ok(salesVolumes);
    }

    /**
     * 获取热卖商品
     * @return
     */
    @GetMapping("/getHotCommodity")
    public Result getHotCommodity(){
        Map<String,Integer> map = new HashMap<>();
        Map<String,String> skuMap = new HashMap<>();
        SimpleDateFormat fmt = new SimpleDateFormat("MM-dd");
        List<ShopDTO> data = shopService.getListOfStores(JwtUtil.getUserIdByToken()).getData();
        if (data == null || data.size() == 0){
            return Result.error("没有店铺信息");
        }
        List<String> shopIds = data.stream().map(ShopDTO::getId).collect(Collectors.toList());
        List<OrderItemBO> hotCommodity = orderService.getHotCommodity(shopIds);
        if( null == hotCommodity || hotCommodity.size() == 0){
            return Result.ok("没有商品信息");
        }
        for(OrderItemBO bo : hotCommodity){
            if (map.containsKey(fmt.format(bo.getPaymentTime()))) {
                int monthPrices = map.get(fmt.format(bo.getPaymentTime())) + (bo.getQuantity() == null?0:bo.getQuantity());
                map.put(fmt.format(bo.getPaymentTime()), monthPrices);
            } else {
                map.put(fmt.format(bo.getPaymentTime()),(bo.getQuantity() == null?0:bo.getQuantity()));
            }
        }
        return Result.ok(MapSortUtil.sortByKeyAsc(map));
    }

}
